import uuid
# from flaskapp.model.db import db, MediaSource
# from sqlalchemy.exc import SQLAlchemyError
from flaskapp.model.mongo import db
from datetime import datetime
import logging
from bson import ObjectId
# Setup logging
logger = logging.getLogger(__name__)


def insert(name: str, url: str, code: str, width: int, height: int) -> bool:
    try:
        current_datetime = datetime.now()
        # info = MediaSource(id=str(uuid.uuid4()), name=name, url=url,
        #                    code=code, width=width, height=height, timestamp=current_datetime)
        # db.session.add(info)
        # db.session.commit()
        info={ "name":name, "url":url,
                            "code":code, "width":width, "height":height, "timestamp":current_datetime}
        ret=db.mediasource.insert_one(info)
        logger.info(f"Inserted mediasource with id: {ret.inserted_id}")
        return True
    except BaseException as e:
        # db.session.rollback()
        logger.error(f"Error inserting mediasource: {e}")
        return False


def delete(id: str) -> bool:
    try:
        # info = MediaSource.query.get(id)
        info=db.mediasource.find_one({"_id":ObjectId(id)})
        if info:
            # db.session.delete(info)
            # db.session.commit()
            ret=db.mediasource.delete_one({"_id":ObjectId(id)})
            logger.info(f"Deleted mediasource with id: {ret.deleted_count}")
            return True
        logger.warning(f"Mediasource with id: {id} not found")
        return False
    except BaseException as e:
        # db.session.rollback()
        logger.error(f"Error deleting mediasource: {e}")
        return False


def update(id: str, name: str, url: str, code: str, width: int, height: int) -> bool:
    try:
        # info = MediaSource.query.get(id)
        info=db.mediasource.find_one({"_id":ObjectId(id)})
        if info:
            info.name = name
            info.url = url
            info.code = code
            info.width = width
            info.height = height
            info.timestamp = datetime.now()  # 更新修改时间
            # db.session.commit()
            ret=db.mediasource.update_one({"_id":ObjectId(id)},info)
            logger.info(f"Updated mediasource with id: {ret.matched_count}")
            return True
        logger.warning(f"Mediasource with id: {id} not found")
        return False
    except BaseException as e:
        # db.session.rollback()
        logger.error(f"Error updating mediasource: {e}")
        return False


def findOneById(id: str) -> dict:
    try:
        row=db.mediasource.find_one({"_id":ObjectId(id)})
        return row
    except BaseException as e:
        logger.error(f"Error deleting user: {e}")
        return 0


def find(page: int = 1, per_page: int = 10) -> dict:
    try:
        logger.info(
            f"Fetching mediasource for page: {page}, per_page: {per_page}")
        # query = MediaSource.query.order_by(MediaSource.timestamp.desc())

        # pagination = query.paginate(
        #     page=page, per_page=per_page, error_out=False)
        # items = [info.to_dict() for info in pagination.items]
        total=db.mediasource.count_documents({})
        media_page=db.mediasource.find({}).sort("timestamp").limit(per_page).skip(per_page*(page-1))
        items=[]
        for r in media_page:
            items.append(r)
        logger.info(
            f"Retrieved {len(items)} mediasource from page {page}, total items: {total}")
        return {
            "items": items,
            "total": total
        }
    except BaseException as e:
        logger.error(f"Error retrieving mediasource: {e}")
        return {
            "items": [],
            "total": 0
        }


def get_media_url() -> dict:
    try:
        media_page=db.mediasource.find({})
        result={}
        for r in media_page:
            print(r)
            result[str(r["_id"])]=r["url"]
        # query = MediaSource.query
        # items = query.all()
        # result = {item.id: item.url for item in items}
        
        logger.info(f"Retrieved {len(result)} MediaSource items")
        return result
    except BaseException as e:
        logger.error(f"Error retrieving MediaSource items: {e.args}")
        return {}
